<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $components = array('Site');

	function index() {
		$this->User->recursive = 0;
		$fields=array('User.login','User.name','User.vote','User.created','User.postcount','User.comcount');
		$cond="User.type>0";		
		list($sort,$order)=$this->Site->getSort('points');
   	$count=$this->User->findCount($cond);			
		$users=$this->User->findAll($cond,$fields,$sort." ".$order,PAGESIZE,$this->pager($count,PAGESIZE),0);
		$this->set('users', $users);
		$this->set('count', $count);   
	}

	function login() {
		$ref=$this->referer('/');

		if($ref[0]=="/" && !preg_match('/users\/login|users\/activate|users\/register/', $ref)) {
			$this->Session->write('redir', $this->referer('/'));
		}

        if (!empty($this->data) && !empty($this->data['User']['login']))
        {
			$this->User->recursive = -1;
			$fields=array('User.id','User.login','User.password','User.name','User.lastseen','User.vote','User.type','User.threshold','User.thread','User.avatar','User.tz');
            $someone = $this->User->find("User.login='".$this->data['User']['login']."' AND User.type>0",$fields);
            if(!empty($someone['User']['password']) && $someone['User']['password'] == md5($this->data['User']['password']))
            {
							$this->User->lastseen($someone['User']['id']);
                $this->Session->write('User', $someone['User']);
				if(isset($this->params['form']['remember'])) {
					$expire=time()+60*60*24*7;
          $dom=$_SERVER['SERVER_NAME'];
          if (strtolower(substr($dom, 0, 4)) == 'www.')  $dom = substr($dom, 4);
     			$dom='.'.$dom;
					setcookie("luser",$someone['User']['id']."-".$someone['User']['login']."-".$someone['User']['password'],$expire,"/",$dom);
				}
				$this->Session->setFlash('Hello, <b>'.$someone['User']['login']."</b>!");
				if($this->Session->check('redir'))
					$this->redirect($this->Session->read('redir'));
				else
					$this->redirect("/");
				exit;
            }
            else
            {
							$this->Session->setFlash("Wrong credentials.","msgerror");
              //$this->set('error', true);
            }
        }
	}

	function auth() {
		list($uid,$ulogin,$upass)=explode("-",$_COOKIE["luser"]);
    $this->User->recursive = -1;
		$fields=array('User.id','User.login','User.password','User.name','User.lastseen','User.vote','User.type','User.threshold','User.thread','User.avatar','User.tz');
    $someone = $this->User->find("User.id={$uid} AND User.login='{$ulogin}' AND User.password='{$upass}' AND User.type>0",$fields);
		if(!empty($someone['User']['password'])) {
			$this->User->lastseen($someone['User']['id']);
			$this->Session->write('User', $someone['User']);
      $this->Session->setFlash('Hello, <b>'.$someone['User']['login']."</b>!");
				if($this->Session->check('redir'))
					$this->redirect($this->Session->read('redir'));
				else
					$this->redirect("/");
		} else {
			$this->Session->setFlash("Wrong credentials.","msgerror");
			$this->redirect("/users/login/");
			//$this->set('error', true);
			//$expire=time()-42000;
			//setcookie("luser","",$expire,"/");
		}
	}

	function checklogin() {
		$this->layout="ajax";
		$l=strtolower($this->data['User']['login']);
		if (!preg_match($this->User->validate['login'],$l)) {
			$this->set('status', "Wrong format.");
			$this->render();
			exit;
		}
		$someone = $this->User->findByLogin($l,"login",null,0);
		if ($someone)
			$this->set('status', "This login is taken.");
		else
			$this->set('status', "Available!");
	}

    function logout() {
		$this->Session->delete('User');
		if(isset($_COOKIE["luser"])) {
	        //$expire=time()-60*60*24*7;
					$expire=1;
					$dom=$_SERVER['SERVER_NAME'];
	        if (strtolower(substr($dom, 0, 4)) == 'www.')  $dom = substr($dom, 4);
	    	$dom='.'.$dom;
			setcookie("luser","",$expire,"/",$dom);
		}
		$this->Session->setFlash('Good bye!');
		$this->redirect('/');
	}

	function view($login = null, $part=null) {
    Configure::load('vars');
		$this->set('ims', Configure::read('ims'));
		$fields=array('User.id','User.login','User.name','User.email','User.im','User.site','User.vote','User.created','User.postcount','User.comcount','User.avatar','User.about');
		//$user = $this->User->find(array('User.login'=>strtolower($login)),$fields,null,0);
    $user = $this->User->find("User.login ='".strtolower($login)."' AND User.type>0",$fields,null,0);
		if (!$login || empty($user)) {
    	$this->Session->setFlash('There is no such user.','msgerror');
			$this->redirect('/users/');
			exit;
    }
		$this->set('user', $user);
		$mypage=false;
		$this->set('mypage', $mypage);

		if($this->luser) {

    if(empty($this->data) && !$part) {
			vendor('func');
			$this->Session->write('imgcode', gencode());
		}
		if(!empty($this->data)) {
  	  if(strlen($this->data['User']['text'])<5)
				$this->User->invalidate('text');
      if($this->data['User']['imgcode']!=$this->Session->read('imgcode'))
				$this->User->invalidate('imgcode');
			if($this->User->validates($this->data)) {
				vendor('func');
        $to=$user['User']['email'];
				$subject="message from user ".$this->luser['login'] ;
				$message='

'.$this->data['User']['text'].'

';
				sendmail($to, $subject, $message, '');
				$this->Session->setFlash('Message sent.');
				$this->redirect('/users/');
			}
		}

		$fields=array('Post.id','Post.title','Post.replies','Post.closed','Post.created','Post.modified','Post.points','Post.rated','Category.name','Category.description');
		$cfields=array('Comment.id','Comment.text','Comment.created','Comment.vote','Comment.del','Post.id','Post.title');
		$vfields=array('Vote.post_id','Vote.comment_id','Vote.value','Vote.created');
		if($user['User']['id']==$this->luser['id']) { // it's me
			$mypage=true;
			$this->set('mypage', $mypage);
			if(!$part) $this->set('vcount',$this->User->Vote->findCount("Vote.user_id=".$this->luser['id']));
		}
			if($part=="topics") {
			// posts
			$cond=array('Post.user_id'=>$user['User']['id']);
			list($sort,$order)=$this->Site->getSort('modified');
     	$count=$user['User']['postcount'];
			$posts=$this->User->Post->findAll($cond,$fields,$sort." ".$order,PAGESIZE,$this->pager($count,PAGESIZE),0);
			$this->set('posts', $posts);
			}
			if($part=="comments") {
			// comments
			$cond=array('Comment.user_id'=>$user['User']['id']);
			list($sort,$order)=$this->Site->getSort('added');
     	$count=$user['User']['comcount'];
			$comments=$this->User->Comment->findAll($cond,$cfields,$sort." ".$order,PAGESIZE,$this->pager($count,PAGESIZE),0);
			$this->set('comments', $comments);
			}
			if($mypage && $part=="votes") {
			// votes
			$cond=array('Vote.user_id'=>$user['User']['id']);
			list($sort,$order)=$this->Site->getSort('votedon');
     	$count=$this->User->Vote->findCount($cond);
			$votes=$this->User->Vote->findAll($cond,$vfields,$sort." ".$order,PAGESIZE,$this->pager($count,PAGESIZE),0);
			$this->set('votes', $votes);
			$this->set('count', $count);
			}
	 		} // logged
			$this->set('part', $part);
	}

	function register() {
		vendor('func');
		if(empty($this->data)) {
			$this->Session->write('imgcode', gencode());
			$this->render();
			exit;
		}
			$this->User->set($this->data);
			$this->User->recursive = 0;
			if(!empty($this->data['User']['login'])) {

            if ($this->User->findByLogin(strtolower($this->data['User']['login'])))
            	$this->User->invalidate('login2');

			}
      if(!empty($this->data['User']['email'])) {

            if ($this->User->findByEmail(strtolower($this->data['User']['email'])))
            	$this->User->invalidate('email2');

			}

			if($this->data['User']['password'] != $this->data['User']['password2'])
				$this->User->invalidate('password2');

			if($this->data['User']['imgcode']!=$this->Session->read('imgcode'))
				$this->User->invalidate('imgcode');

			if($this->User->save()) {
				$u=$this->User->find("User.id=LAST_INSERT_ID() AND User.type=0",array("User.email", "MD5(CONCAT(CAST(id AS CHAR), login)) as code"),null,-1);
				$to=$u['User']['email'];
				$subject="activation";
				$message='
Your data:
* login: '.$this->data['User']['login'].'
* password: '.$this->data['User']['password'].'

Click the link to activate your account:
http://'.$_SERVER['SERVER_NAME'].'/users/activate/'.$u[0]['code'].'

Ignore this message if you did not register.
';
				sendmail($to, $subject, $message, '');
				$this->Session->setFlash('Account created.');
				$this->redirect('/users/activate/');
			} else {
				$this->Session->setFlash('Fill required fields.','msgerror');
			}
	}

	function activate($a=null) {
		if(!$a) {
			$this->set('act', 1);
			$this->render();
			exit;
		}
		$u=$this->User->find("User.type=0 AND MD5(CONCAT(CAST(id AS CHAR), login))='{$a}'",array("User.id","User.type","User.login"),null,-1);
		if (isset($u['User'])) {
    	Configure::load('settings');
			$pnt=Configure::read('points');
			$this->User->id = $u['User']['id'];
			$u['User']['type']=1;
			$u['User']['vote']=$pnt['start'];
			$u['User']['lastseen']=date('Y-m-d H:i:s');
			if($this->User->save($u)) {
				$this->set('user',$u);
			}
		}
		else {
    	$this->Session->setFlash('There is no such user.','msgerror');
			$this->redirect('/users/register/');
		}
	}

	function profile() {
		$this->checkSession();
        Configure::load('vars');
		$this->set('ims', Configure::read('ims'));
		$this->set('tzs', Configure::read('tz'));
		if(empty($this->data)) {
			$this->User->recursive = 0;
			$this->data = $this->User->read(array("id","login","name","site","im","email","notify","avatar","about","threshold",'thread','tz'), $this->luser['id']);
			if($this->data['User']['im']) {
				list($this->data['User']['ims'],$this->data['User']['im']) = explode("/", $this->data['User']['im'], 2);
			}
			$this->set("a",$this->data['User']['avatar']);
		} else {
			$this->User->recursive = 0;
			$ou=$this->User->read(array("id","password"), $this->luser['id']);
			if($ou['User']['password']!=$this->luser['password']) {
				$this->redirect('/users/');
				exit();
			}
			$this->User->set($this->data);
			// delete avatar
			if(!empty($this->params['form']['delavatar'])) {
				$this->data['User']['avatar']=null;
				@unlink(WWW_ROOT."pic/".$this->luser['login'].".jpg");
			}

			// save avatar
      if(!empty($this->params['form']['avatar']) && $this->params['form']['avatar']['error']==0) {
				$this->params['form']['avatar']['name'] = $this->luser['login'];
				if(!$this->_saveAvatar($this->params['form']['avatar'])) {
					$this->User->invalidate('fileavatar');
				}
				else {
					$this->data['User']['avatar']=1;
				}
			}

			if($this->User->save($this->data)) {
				$this->Session->setFlash('Profile saved.');
				$fields=array('User.id','User.login','User.password','User.name','User.lastseen','User.vote','User.type','User.threshold','User.thread','User.avatar','User.tz');
				$this->User->recursive = 0;
				$u=$this->User->read($fields,$this->luser['id']);
				$this->Session->write('User', $u['User']);
				$this->redirect('/user/'.$u['User']['login'].'/');
			} else {
				$this->Session->setFlash('Fix errors.','msgerror');
			}
		}
	}

    function _saveAvatar($file) {
		vendor('imgresize');
		$ext=array(1=>'gif', 2=>'jpg', 3=>'png');
		$name=WWW_ROOT."pic/".$file['name'];
    if (move_uploaded_file($file['tmp_name'], $name)) {
          $rsz = new ImgResize;
					if(!$rsz->resize($name,$name.".jpg",48)) return false;

    		// delete old avatar
			  /*$oldav=WWW_ROOT."pic/".$this->luser['login'].".jpg";
        if (file_exists($oldav)) {
					unlink($oldav);
			  }*/

				//return $ext[$imginfo[2]];
				return true;
        } else {
            // TODO: Set error message if move_uploaded_file fails
            return false;
        }
	}

	function password() {
		$this->checkSession();
		$this->User->recursive = 0;
		if(!empty($this->data)) {
			$op=$this->User->read(array("id","password"), $this->luser['id']);
			$this->User->set($this->data);

		if ($op['User']['password']!=md5($this->data['User']['oldpassword']))
			$this->User->invalidate('oldpassword');
        if($this->data['User']['password'] != $this->data['User']['password2'])
			$this->User->invalidate('password2');

    if($this->User->save()) {
				$this->Session->setFlash('Password changed.');
				$this->redirect('/user/'.$this->luser['login'].'/');
		} else {
				$this->Session->setFlash('Fix errors.','msgerror');
		}
		}
		else {
			$this->data=$this->User->read(array("id"), $this->luser['id']);
		}
	}

	function admin_index() {
		$this->checkAdmin(); $this->layout='admin';
		Configure::load('vars');
		$this->set('ims', Configure::read('ims'));
		$this->User->recursive = 0;
    $count=$this->User->findCount();
		list($sort,$order)=$this->Site->getSort('regdate');
		$this->set('count',$count);
		$this->set('users', $this->User->findAll(null,null,$sort." ".$order,APAGESIZE,$this->pager($count,APAGESIZE),0));
	}

	function admin_edit($id = null) {
		$this->checkAdmin(); $this->layout='admin';
    Configure::load('vars');
		$this->set('utype', Configure::read('utype'));
		$this->set('ims', Configure::read('ims'));
		if(empty($this->data)) {
			if(!$id) {
				$this->redirect('/admin/users/');
				exit;
			}
			$this->User->recursive=0;
			$this->data = $this->User->read(null, $id);
      if($this->data['User']['im']) {
				list($this->data['User']['ims'],$this->data['User']['im']) = explode("/", $this->data['User']['im'], 2);
			}
		} else {
			$this->cleanUpFields();
			if($this->User->save($this->data)) {
				$this->Session->setFlash('User modified.');
				$this->redirect('/admin/users/');
			} else {
				$this->Session->setFlash('Fix errors.',"msgerror");
			}
		}
	}

	function admin_delete($id = null) {
		$this->checkAdmin(); $this->layout='admin';
		if(!$id) {
			$this->redirect('/admin/users/');
			exit;
		}
		if($this->User->del($id)) {
			$this->Session->setFlash('User deleted: id '.$id.'');
			$this->redirect('/admin/users/');
		}
	}

}
?>